package com.hz.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;


public class Download {

    public static void download(String urlString, String filename, String savePath) {
        OutputStream os = null;
        InputStream is = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            //设置请求超时为5s
            con.setConnectTimeout(5 * 1000);
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File sf = new File(savePath);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            os = new FileOutputStream(sf.getPath() + File.separator + filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            if (os != null) {
                try {
                    os.close(); // 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close(); // 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 生成.json格式文件
     */
    public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
        // 标记文件生成是否成功
        boolean flag = true;

        // 拼接文件完整路径
        String fullPath = filePath + File.separator + fileName + ".json";

        // 生成json格式文件
        Writer write = null;
        try {
            // 保证创建一个新文件
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();

            // 格式化json字符串
            // jsonString = JsonFormatTool.formatJson(jsonString);

            // 将格式化后的字符串写入文件
            write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        } finally {
            if (write != null) {
                try {
                    // write.flush();
                    write.close(); // 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 返回是否成功的标记
        return flag;
    }

    /**
     *
     * @return  省市区jsonObject
     */
    public static JSONObject readJsonFile() {
        JSONObject jsonObject = new JSONObject();
        String jsonStr = "";
        try {
            ClassPathResource classPathResource = new ClassPathResource("city.json");
            InputStream inputStream =classPathResource.getInputStream();
            Reader reader = new InputStreamReader(inputStream, "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            jsonObject = JSON.parseObject(jsonStr);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
            return new JSONObject();
        }

    }


    /**
     *
     * @param key
     * @param jsonString
     * @return
     */
    public static String childrenToOther(String key, String jsonString){
        JSONObject jsonObject = JSON.parseObject(jsonString);
        jsonObject.put(key, jsonObject.get("children"));
        jsonObject.remove("children");
        return JSON.toJSONString(jsonObject);
    }

}
